#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>

#include <assert.h>

//------------------------------------------------------

#include "../Peer/DEV/partition/buffermap.h"
#include "structure.h"
#include "config.h"
#include "getpieces.h"

#include "test_getpiece_query.h"
//------------------------------------------------------

//--- à deplacer ---
extern struct database db; 


/**
 * \brief Forme la requête du getpiece à envoyer au client .
 *
 * \param cl le client leecher
 * \param bm le buffermap des pièces à télécharger du client
 * \return la requête getpiece.
 */
char * getpieces_query(char * query, int gp_file, _t_buffermap bmp){
  buffermap bm = create_buffermap(bmp, db.tab_file[gp_file].size);

   assert(bmp != 0);
  
  struct file * f = &db.tab_file[gp_file];

  int bytes_read = sprintf(query, "getpieces %.32s [", f->key);
  int j;
  
  for (j=0; j<bm.size ;j++){
  	if (bm.buffer[j] == '1'){
  		bytes_read += sprintf(query+bytes_read, "%d ", j);
  	}
  }
  sprintf(query+bytes_read-1, "]");

  return query;
}
  		

#ifdef TEST
int main(){
	char query[GP_QUERY_SIZE];
	int gp_file = 0;
	// initialisation de la base de données
	db.nb_file = 1;
	strcpy(db.tab_file[gp_file].name, "TEST_FILE")	;
	db.tab_file[gp_file].size = 30000; 
	db.tab_file[gp_file].piece_size = 2048;
	strcpy(db.tab_file[gp_file].key, "abc");
	db.tab_file[gp_file].buffer_map = 28;
	db.tab_file[gp_file].clients = NULL; 
		
	//buffermap bm = create_buffermap(db.tab_file[gp_file].buffer_map, db.tab_file[gp_file].size);
	//print_buffermap(bm);
	//printf("taille du buffermap : %d\n", bm.size);
	
	printf("query = %s\n", getpieces_query(query, gp_file, bmp));
}
#endif
